package com.iakuil.app.common.core.jsr303.validators;

import com.iakuil.app.common.core.jsr303.constraints.Ids;
import com.iakuil.app.common.core.util.CollectionUtils;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.Collection;

/**
 * ID集合校验器
 *
 * @author Kai
 * @date 2024-06-14
 */
public class IdsValidatorForCollection implements ConstraintValidator<Ids, Collection<Long>> {

    private String msg;

    @Override
    public void initialize(Ids constraintAnnotation) {
        this.msg = constraintAnnotation.message();
    }

    @Override
    public boolean isValid(Collection<Long> ids, ConstraintValidatorContext context) {
        // 忽略空值情况
        if (ids == null) {
            return true;
        }

        if (CollectionUtils.hasNull(ids)) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()
                .replaceAll("\\{value}", msg)).addConstraintViolation();
            return false;
        }

        return true;
    }
}
